
var app = require('express')();
var bodyParser = require('body-parser');
var fs = require('fs');
const log4js = require('log4js');

const fileName = 'client.log'
// 删除旧日志文件
// if (fs.existsSync(fileName)) {
//   fs.unlinkSync(fileName)
// }


// 重新创建日志文件
log4js.configure({
  appenders: { CLIENT: { type: 'file', filename: fileName } },
  categories: { default: { appenders: ['CLIENT'], level: 'info' } }
});
const logger = log4js.getLogger('CLIENT');

//设置允许跨域访问该服务.
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Methods', '*');
  next();
})

// POST的BODY解释
var textParser = bodyParser.text({type:'text/plain'}) // body的内容为字符串 
// var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post('/postinfo', textParser, function (req, res) {
	try {
		logger.info(req.body);
	} catch (error) {
		res.send(error.message)
		return
	}
  res.send('OK!')
});

app.post('/posterror', textParser, function (req, res) {
	try {
		logger.error(req.body);
	} catch (error) {
		res.send(error.message)
		return
	}
	res.send('OK!')
});

app.get('/print', function(req, res) {
	try {
		fs.readFile(fileName, "utf-8", function(error, data) {
			if (error) return res.send("读取文件失败,内容是" + error.message);
			res.send(data);
		});
	} catch (error) {
		res.send(error.message)
	}
}) 

var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("应用实例，访问地址为 http://%s:%s", host, port)
})
